﻿using System.Collections.Generic;
using System.Web;

using GKFX.Common.UI.Helpers;
using GKFX.GeoIP;
using Century.Model;
using GKFX.Common.Business.BOL.Common;
using System.Linq;
using GKFX.Business.Repository;

namespace GKFX.Common.UI.CookieManager
{
    public class RequestManager
    {
        /// <summary>
        /// Check all request in begin request.
        /// </summary>
        /// <param name="request"></param>
        public static void CheckUserRequest(HttpRequest request)
        {
            //NetReferCookieHandler(request);
            RedirectToTrueSite(request);
        }

        #region [ Private Methods ]

        /// <summary>
        /// Method to set cookie for net refer
        /// </summary>
        /// <param name="request"></param>
        private static void NetReferCookieHandler(HttpRequest request)
        {
            if (
                null != request.Params[ConfManager.Instance.Common.NetReferRequestParamName.ConfigValue] &&
                (null == request.Cookies[ConfManager.Instance.CookieManager.NetReferCookieName.ConfigValue] || string.IsNullOrEmpty(request.Cookies[ConfManager.Instance.CookieManager.NetReferCookieName.ConfigValue].Value))
               )
            {
                CookieWriter.SetCookieForAllDomains(ConfManager.Instance.CookieManager.NetReferCookieName.Value,
                    request.Params[ConfManager.Instance.Common.NetReferRequestParamName.ConfigValue]);
            }
        }


        /// <summary>
        /// Method to parse url and redirect user to the true website and 
        /// also set the cookies
        /// </summary>
        /// <param name="request"></param>
        private static void RedirectToTrueSite(HttpRequest request)
        {
            //if (request.UrlReferrer != null && request.UrlReferrer.AbsolutePath.ToLower() == "/webtrader/webtrader.html")
            //{
            //    if (!request.UrlReferrer.Host.ToLower().Contains("gkfx.com") && request.Url.Host.Contains("gkfx.com"))
            //    {
            //        UrlParser parsedRefURL = new UrlParser(request.UrlReferrer);
            //        CountrySite site = PersistData.AvailableSites.FirstOrDefault(c => c.SiteAddress.ToLower().Contains(parsedRefURL.Domain.ToLower()));
            //        if (site != null)
            //        {
            //            HttpContext.Current.Response.Redirect(site.DemoApplicationUrl);
            //        }
            //    }
            //}
            //Check ignore urls such as styles and scripts
            foreach (string ignorePath in ConfManager.Instance.CookieManager.IgnoreUrlList.Value)
            {
                if (request.Url.AbsoluteUri.ToLower().Contains(ignorePath.ToLower()))
                {

                    return;
                }
            }
            string url = request.Url.AbsoluteUri;

            UrlParser parsedURL = new UrlParser(url);

            //check for separate sites
            if (ConfManager.Instance.CookieManager.SeparateSites.ConfigValue.ToLower().Contains(parsedURL.Domain.ToLower()))
            {
                List<string> separateDomains = ConfManager.Instance.CookieManager.SeparateSites.Value;
                string cookieValue = separateDomains.Find(c => c.ToLower().Contains(parsedURL.Domain.ToLower())).Split(':')[1];
                CookieWriter.SetCookieForAllDomains(ConfManager.Instance.CookieManager.CountryCookieName.ConfigValue, cookieValue);
                if (string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[ConfManager.Instance.CookieManager.CountryCookieName.ConfigValue].Value)
                     || HttpContext.Current.Request.Cookies[ConfManager.Instance.CookieManager.CountryCookieName.ConfigValue].Value.ToLower() != cookieValue.ToLower())
                {
                    HttpContext.Current.Response.Redirect(parsedURL.CurrentAddress + parsedURL.PathAndQuery);
                }
                return;

            }
            if (string.IsNullOrEmpty(parsedURL.SiteAddress))
            {
                //parsedURL.CleanURL.Replace(
                string siteAddress = string.Empty;
                string sitePath = GetSiteForCurentUser(request, parsedURL, out siteAddress);
                CookieWriter.SetCookieForAllDomains(ConfManager.Instance.CookieManager.CountryCookieName.ConfigValue, sitePath);
                HttpContext.Current.Response.Redirect(siteAddress + parsedURL.PathAndQuery);
            }
            else
                if (
                         parsedURL.CurrentAddress.ToLower().Replace("www.", string.Empty).Replace("https://", string.Empty).Replace("http://", string.Empty).Replace(":443", string.Empty)
                         !=
                         parsedURL.SiteAddress.ToLower().Replace("www.", string.Empty).Replace("https://", string.Empty).Replace("http://", string.Empty).Replace(":443", string.Empty)
                     )
                {
                    // for https requests
                    string newAddress = parsedURL.SiteAddress.Replace("http", parsedURL.Protocol);
                    CookieWriter.SetCookieForAllDomains(ConfManager.Instance.CookieManager.CountryCookieName.ConfigValue, parsedURL.SitePath);
                    HttpContext.Current.Response.Redirect(newAddress + parsedURL.PathAndQuery);
                }
                else
                {
                    CookieWriter.SetCookieForAllDomains(ConfManager.Instance.CookieManager.CountryCookieName.ConfigValue, parsedURL.SitePath);

                    if (string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[ConfManager.Instance.CookieManager.CountryCookieName.ConfigValue].Value)
                   || HttpContext.Current.Request.Cookies[ConfManager.Instance.CookieManager.CountryCookieName.ConfigValue].Value.ToLower() != parsedURL.SitePath.ToLower())
                    {
                        HttpContext.Current.Response.Redirect(parsedURL.CurrentAddress + parsedURL.PathAndQuery);
                    }
                }


        }

        /// <summary>
        /// Find site for current user
        /// </summary>
        /// <param name="request"></param>
        /// <param name="parsedURL"></param>
        /// <param name="siteAddress"></param>
        /// <returns></returns>
        private static string GetSiteForCurentUser(HttpRequest request, UrlParser parsedURL, out string siteAddress)
        {
            //Get country code by user ip;
            string countryCode = GeoIPService.instance.GetCountryCode(request.UserHostAddress);
            string sitePath = countryCode;

            if (string.IsNullOrEmpty(sitePath))
            {
                //go to global fsa site if ip not find
                sitePath = GetGlobalSite(parsedURL, true, out siteAddress);
            }
            else
            {
                //Find country from county table by geo ip country code
                CommonCountry country = new CommonCountryBSO().Find(c => c.Code.ToLower() == countryCode.ToLower());
                if (country == null)
                {
                    //go to global fsa site if country does not exist in our list
                    sitePath = GetGlobalSite(parsedURL, true, out siteAddress);
                }
                else
                {

                    if (!PersistData.AvailableSites.Any(c => c.Path.ToLower() == sitePath.ToLower()))
                    {
                        //go to global fsa or non fsa site if there is no site for finded country
                        sitePath = GetGlobalSite(parsedURL, country.IsFSA, out siteAddress);
                    }
                    else
                    {
                        //Go to special site by finded country code
                        CountrySite site = PersistData.AvailableSites.First(c => c.Path.ToLower() == sitePath.ToLower());
                        sitePath = site.Path;
                        siteAddress = site.SiteAddress;
                    }
                }
            }
            return sitePath;
        }

        /// <summary>
        /// Method to find global web site for fsa or non fsa countries
        /// </summary>
        /// <param name="parsedURL"></param>
        /// <param name="isFSA"></param>
        /// <param name="siteAddress"></param>
        /// <returns></returns>
        private static string GetGlobalSite(UrlParser parsedURL, bool isFSA, out string siteAddress)
        {
            if (isFSA)
            {
                CountrySite site = PersistData.AvailableSites.Find(c => c.Path.ToLower() == ConfManager.Instance.CMS.FsaIntSitePath.ConfigValue.ToLower());
                siteAddress = site.SiteAddress;
                return site.Path;
            }
            else
            {
                CountrySite site = PersistData.AvailableSites.Find(c => c.Path.ToLower() == ConfManager.Instance.CMS.NonFsaIntSitePath.ConfigValue.ToLower());
                siteAddress = site.SiteAddress;
                return site.Path;
            }
        }

        #endregion
    }
}
